package com.ds.infrastructure.hyperspace.container.flow.handler.http;

import com.ds.infrastructure.hyperspace.common.Container;
import com.ds.infrastructure.hyperspace.common.flow.FlowHandlerPipeline;
import com.ds.infrastructure.hyperspace.common.flow.handler.PreFlowHandler;
import com.ds.infrastructure.hyperspace.container.flow.context.HyperspaceDuplexFlowContext;
import lombok.extern.slf4j.Slf4j;

/**
 * usage eg:
 *  -   handler: httpHeaderSetterPreHandler
 *      handlerParams: [headerName, headerValue, headerName, headerValue]
 * @author  Weishaoying
 */
@Slf4j
public class HttpHeaderSetterPreFlowHandler implements PreFlowHandler<HyperspaceDuplexFlowContext> {

    private volatile String[] params;

    @Override
    public void handleInput(HyperspaceDuplexFlowContext duplexFlowContext, Object data) {
        if (data != duplexFlowContext.getRequestStartState() || params == null || params.length < 1) {
            return;
        }
        int i = 0;
        while (i < params.length) {
            duplexFlowContext.setContextHeader(params[i], params[i + 1]);
            i += 2;
        }
    }

    @Override
    public String handlerName() {
        return "httpHeaderSetterPreHandler";
    }

    @Override
    public void initHandlerParameters(Container container, FlowHandlerPipeline pipeline, String[] handlerParams) {
        params = handlerParams;
    }

}
